<template>
  <n-card class="coupon" :class="{ 'coupon-disabled': isgetcoupon }">
    <h4>¥{{ item.price }}</h4>
    <p>适用{{ o[item.type] }}：{{ item.value.title }}</p>
    <p class="!text-xs mt-3">有效期：
      <n-time :time="new Date(item.start_time)"/>
      ~
      <n-time :time="new Date(item.end_time)"/>
    </p>

    <template #footer>
      <div class="flex justify-end">
        <n-button
            size="small"
            :type="isgetcoupon ? '' : 'warning'"
            :disabled="isgetcoupon"
            :loading="loading"
            @click="submit"
        >{{ isgetcoupon ? '已领取' : '立即领取' }}
        </n-button
        >
      </div>
    </template>
  </n-card>
</template>

<script setup>
// 引入 naive-ui
import {NCard, NButton, NTime, createDiscreteApi} from "naive-ui";

// 类型
const o = {
  course: "课程",
  column: "专栏",
};

// 引用声明
const props = defineProps({
  item: {
    type: Object,
    required: true,
  },
});

// 加载
const loading = ref(false);

// 是否已领取
const isgetcoupon = ref(props.item.isgetcoupon)

// 立即领取事件
const submit = () => {
  const {message} = createDiscreteApi(['message'])
  if (isgetcoupon.value) {
    return message.error("你已经领取过了")
  }

  useHashAuth(async () => {
    loading.value = true;
    const {error, data} = await useReceiveUserCouponApi({
      coupon_id: props.item.id
    })

    loading.value = false;
    if (error.value) return;

    message.success("领取成功");

    isgetcoupon.value = true;

  })
}

</script>

<style scoped lang="css">
.coupon {
  @apply mb-5 bg-orange-500 border-0;
}

.coupon h4 {
  @apply text-2xl mb-2 font-bold text-white;
}

.coupon p {
  @apply text-sm text-light-300;
}

.coupon-disabled {
  @apply !bg-gray-300;
}
</style>
